<template>
	<view>
		<uni-nav-bar title="" :border="false" @clickLeft="back" @clickRight="submit" fixed>
			<block slot="left">
				<uni-icons type="left" size="23"></uni-icons>
			</block>
			<block slot="right">
				<view style="color: #2699FB;" class="padding-right-sm text-xl">交卷</view>
			</block>
		</uni-nav-bar>

		<view class="padding">
			<view class="flex align-end justify-between top-hight">
				<!-- 倒计时 -->
				<view class=" flex align-center">
					剩余时间：
					<u-count-down :time="duration * 60 * 1000" format="HH:mm:ss" autoStart millisecond
						@change="onChange" @finish="timeFinishHandle">
						<view class="time">
							<view class="time__custom">
								<text
									class="time__custom__item">{{ timeData.hours>10?timeData.hours:'0'+timeData.hours}}</text>
							</view>
							<text class="time__doc">:</text>
							<view class="time__custom">
								<text class="time__custom__item">{{ timeData.minutes }}</text>
							</view>
							<text class="time__doc">:</text>
							<view class="time__custom">
								<text class="time__custom__item">{{ timeData.seconds }}</text>
							</view>
						</view>
					</u-count-down>
				</view>
				<!-- 当前第几题 -->
				<view class="flex align-center">
					<view class="text-xxl">{{curSwiper + 1}}</view>
					<view style="color: #989898;line-height: 100%;">/{{paperCount}}</view>
				</view>
			</view>
			<view class="under-line padding-top"></view>


			<swiper class="swiper" :style="{height: scrollHeight + 'px'}" :current="curSwiper"
				@change="swiperChangeHandle">
				<swiper-item v-for="(item,questionIndex) in questions" :key="questionIndex">
					<!-- 考试题 -->
					<view>
						<view class="text-xl text-bold padding-top padding-bottom" style="letter-spacing: 3upx;">
							{{`【${item.type}】`}}{{item.text}}
						</view>
						<view v-if="item.type === '单选' || item.type === '判断' ">
							<view v-for="(option,index) in item.options" :key="index" class="padding-bottom-sm">
								<view :style="{backgroundColor:option.bgColor,color: option.color}"
									@click="selectItemHandle(questionIndex,index)"
									class="flex align-center padding-left"
									style="height: 80upx;border-radius: 10upx;transition: all .2s;">
									<view class="text-lg">
										{{`${option.value}.${option.text}`}}
									</view>
								</view>
							</view>
						</view>
						<view v-if="item.type === '多选'">
							<view v-for="(option,index) in item.options" :key="index" class="padding-bottom-sm">
								<view :style="{backgroundColor:option.bgColor,color: option.color}"
									@click="selectMultipleItemHandle(questionIndex,index)"
									class="flex align-center padding-left"
									style="height: 80upx;border-radius: 10upx;transition: all .2s;">
									<view class="text-lg">
										{{`${option.value}.${option.text}`}}
									</view>
								</view>
							</view>
						</view>
						<view v-if="item.type === '填空'">
							<view class="padding-top padding-bottom-sm">
								<u--input v-model="item.selected" style="background-color: #f1f1f1;" class="text-lg"
									@change="fillBlankHandle(questionIndex,item.selected)" placeholder="请输入答案"
									border="surround" clearable></u--input>
							</view>
						</view>
					</view>

				</swiper-item>
			</swiper>
		</view>

		<view class="bottom flex justify-between padding-lg">
			<view class="flex">
				<view class="flex align-center">
					<image src="/static/exams/true.png" alt="" style="width: 40upx;height: 40upx;" />
					<view class="text-df padding-left-xs" style="color: #2699FB;">0</view>
				</view>
				<view class="flex align-center padding-left">
					<image src="/static/exams/false.png" alt="" style="width: 40upx;height: 40upx;" />
					<view class="text-xk padding-left-xs text-gray">0</view>
				</view>
			</view>
			<view class="flex align-center" @click="openQuestionModal">
				<image src="/static/exams/items.png" alt="" style="width: 40upx;height: 40upx;" />
			</view>
		</view>

		<view>
			<u-modal :show="isShowQuestionModal" width="650rpx" :showCancelButton="false" :showConfirmButton="false"
				closeOnClickOverlay @close="closeModal">
				<view style="width: 100%;" class="flex justify-center">
					<view class="container slot-content padding-left-sm"
						:style="{gridTemplateRows: `repeat(${Math.floor(questions.length / 4)}, 80rpx)`}">
						<view v-for="(question,index) in questions" :key="index"
							@click="clickQuestionModalItemHandle(index)"
							:style="{backgroundColor: index === curSwiper ? '#f30004' : '#2699FB'}"
							class="text-white padding-xs container-item flex justify-center align-center" style="border-radius: 10upx;">
							<view>
							{{`第${index + 1}题`}}
							</view>
						</view>
					</view>
				</view>
			</u-modal>
		</view>
	</view>
</template>

<script>
	import {
		showConfirm
	} from '@/utils/common'
	import {
		getQuestions,
		submit,
		updateStatus
	} from '@/api/exams.js'
	export default {
		onReady() {
			const _this = this
			uni.getSystemInfo({ //调用uni-app接口获取屏幕高度
				success(res) { //成功回调函数
					let wHeight = res.windowHeight //windoHeight为窗口高度，主要使用的是这个
					let titleH = uni.createSelectorQuery().select(".top-hight"); //想要获取高度的元素名（class/id）
					titleH.boundingClientRect(data => {
						_this.scrollHeight = wHeight - data.top - 60 //计算高度：元素高度=窗口高度-元素距离顶部的距离（data.top）
						console.log(_this.scrollHeight)
					}).exec()
				}
			})
		},
		onLoad(options) {
			this.examid = options.examId
			this.getQuestionsHandle()
		},
		data() {
			return {
				curSwiper: 0,
				isShowQuestionModal: false,
				examid: undefined,
				scrollHeight: 0,
				options: {
					effect: 'ative'
				},
				timeData: {},
				paperCount: 50,
				duration: undefined,
				passingScore: undefined,
				totalScore: undefined,
				questions: [],
				answerArr: []
			}
		},

		methods: {
			closeModal() {
				this.isShowQuestionModal = false
			},
			swiperChangeHandle(e) {
				this.curSwiper = e.detail.current
			},
			clickQuestionModalItemHandle(index) {
				this.isShowQuestionModal = false
				this.curSwiper = index
			},
			openQuestionModal() {
				this.isShowQuestionModal = true
			},
			timeFinishHandle() {
				const that = this
				uni.showModal({
					title: '时间结束，是否重新考试？',
					content: "",
					cancelText: '取消',
					confirmText: '确定',
					success: function(res) {
						if (res.confirm) {
							window.location.reload()
						} else {
							that.submit()
						}
					},
					fail(res) {}
				})
			},
			getQuestionsHandle() {
				const that = this
				getQuestions(this.examid).then(res => {
					if (res.data) {
						let exam = res.data
						that.duration = exam.duration
						that.passingScore = exam.passingScore
						that.totalScore = exam.totalScore
						that.questions = exam.questions
						that.initQuestion()
						that.paperCount = that.questions.length
						that.updateToStarted()
					}
				})
			},
			initQuestion() {
				this.questions.forEach(item => item.isTrue = false)
			},
			updateToStarted() {
				updateStatus(this.examid).then(res => {

				})
			},
			back() {
				const that = this
				uni.showModal({
					title: '是否要退出考试？',
					content: "",
					cancelText: '取消',
					confirmText: '确定',
					success: function(res) {
						if (res.confirm) {
							that.toPage('/pages/work/exams/index')
						}
					},
					fail(res) {}
				})
			},
			submit() {
				// 错题id集合
				let failIdList = this.questions.filter(item => !item.isTrue).map(obj => obj.id)
				let score = 0
				if (failIdList.length < this.questions.length) {
					// 考试得分
					score = this.questions.filter(item => item.isTrue).map(obj => obj.score).reduce((total, num) => total +
						num)
				}
				// 是否通过
				let isPass = score > this.passingScore
				let data = {
					examId: this.examid,
					score: score,
					isPass: isPass,
					failIdList: failIdList
				}
				submit(data).then(res => {
					let obj = res.data
					this.toPage(
						`/pages/work/exams/end?totalScore=${obj.totalScore}&accuracyRate=${obj.accuracyRate}&examDuration=${obj.examDuration}&totalWrong=${obj.totalWrong}`
					)
				})
			},
			toPage(toUrl) {
				uni.navigateTo({
					url: toUrl
				})
			},
			onChange(e) {
				this.timeData = e
			},
			isRealAnswer(questionIndex, optionIndex) {
				let question = this.questions[questionIndex]
				let curOption = question.options[optionIndex]
				switch (question.type) {
					case '单选':
						if (curOption.correct) {
							question.isTrue = true
						} else {
							question.isTrue = false
						}
						break;
					case '多选':
						if (question.options.every(item => item.correct === item.selected)) {
							question.isTrue = true
						} else {
							question.isTrue = false
						}
						break;
					case '判断':
						if (curOption.correct) {
							question.isTrue = true
						} else {
							question.isTrue = false
						}
						break;
					case '填空':
						if (curOption.correct) {
							question.isTrue = true
						} else {
							question.isTrue = false
						}
						break;
				}
			},
			selectItemHandle(questionIndex, index) {
				let options = this.questions[questionIndex].options
				options.forEach(item => {
					item.bgColor = '#f1f1f1'
					item.color = '#5f5f5f'
					item.selected = false
				})
				options[index].bgColor = '#2699FB'
				options[index].color = '#fff'
				options[index].selected = true
				this.isRealAnswer(questionIndex, index)
			},
			selectMultipleItemHandle(questionIndex, index) {
				// 取消的
				let selectedOption = this.questions[questionIndex].options[index]
				if (selectedOption.bgColor === '#2699FB') {
					selectedOption.bgColor = '#f1f1f1'
					selectedOption.color = '#5f5f5f'
					selectedOption.selected = false
				} else {
					// 选中的
					selectedOption.bgColor = '#2699FB'
					selectedOption.color = '#fff'
					selectedOption.selected = true
				}
				this.isRealAnswer(questionIndex, index)
			},
			fillBlankHandle(questionIndex, text) {
				let question = this.questions[questionIndex]
				if (question.options[0].text === text) {
					question.isTrue = true
				} else {
					question.isTrue = false
				}
			},
			onTouchMove(val) {
				console.log(val)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.time {
		@include flex;
		align-items: center;

		&__custom {
			margin-top: 4px;
			width: 22px;
			height: 22px;
			background-color: #000;
			border-radius: 4px;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;

			&__item {
				color: #fff;
				font-size: 12px;
				text-align: center;
			}
		}

		&__doc {
			color: $u-primary;
			padding: 0px 4px;
		}

		&__item {
			color: #606266;
			font-size: 15px;
			margin-right: 4px;
		}
	}

	.under-line {
		position: relative;

		&::after {
			content: "";
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 1px;
			background-color: #e1e1e1;
		}
	}

	.bottom {
		position: fixed;
		bottom: 0;
		box-shadow: 1px 1px 1px 0 rgba(0, 0, 0, 0.1), -1px -1px 3px 0 rgba(0, 0, 0, 0.1);
		width: 100%;
		height: 80upx;
	}

	.container {
		display: grid;
		grid-template-columns: repeat(4, 150rpx);
		.container-item {
			width: 130upx;
			height: 70upx;
		}
	}
</style>